package com.pinhuba.bams.view;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import org.apache.http.protocol.HTTP;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.pinhuba.bams.R;
import com.pinhuba.bams.framework.ConfigProperties;
import com.pinhuba.bams.framework.ErrorCode;
import com.pinhuba.bams.framework.UrlType;
import com.pinhuba.bams.framework.controller.Controller;
import com.pinhuba.bams.framework.controller.DocDownloadCallBackListener;
import com.pinhuba.bams.framework.controller.DocDownloadLoadManager;
import com.pinhuba.bams.framework.controller.ErrorListener;
import com.pinhuba.bams.framework.Params;
import com.pinhuba.bams.framework.util.JsonHandle;
import com.pinhuba.bams.framework.util.Loger;
import com.pinhuba.bams.framework.util.PhoneStateUtil;
import com.pinhuba.bams.framework.util.SharePrefsHelper;
import com.pinhuba.bams.framework.util.ToastHelper;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class AnnounceDetailActivity extends Activity {
	private LinearLayout detailLayout;
	private RelativeLayout toptitleLayout;
	private Button backBtn;
	private Button homeBtn;
	private TextView titleTv;
	private ProgressDialog progressDialog;

	private ListView listView;
	private List<HashMap<String, Object>> list;
	private DetailAdapter adapter;
	private SharePrefsHelper spHelper;

	private String id;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.announce_detail);
		if (!judgeTranslateValue()) {
			ToastHelper.showShortMsg(R.string.unknown_exception_happen);
			initTopView();
			initTopData();
			setTopListener();
		} else {
			initView();
			initData();
			setListener();
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	@Override
	protected void onPause() {
		super.onPause();
	}

	private boolean judgeTranslateValue() {
		id = getIntent().getStringExtra("id");
		if (id == null) {
			return false;
		}
		return true;
	}

	private void initTopView() {
		detailLayout = (LinearLayout) findViewById(R.id.detail);
		toptitleLayout = (RelativeLayout) findViewById(R.id.toptitle);
		backBtn = (Button) toptitleLayout.findViewById(R.id.back_btn);
		homeBtn = (Button) toptitleLayout.findViewById(R.id.home_btn);
		titleTv = (TextView) toptitleLayout.findViewById(R.id.title);
	}

	private void initView() {
		initTopView();
		progressDialog = new ProgressDialog(this);
	}

	private void initTopData() {
		titleTv.setText(R.string.announce_detail);
		detailLayout.setVisibility(View.INVISIBLE);
	}

	private void initData() {
		initTopData();
		progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		spHelper = new SharePrefsHelper(this);
		String tempMsg = getResources().getString(R.string.getingdata) + titleTv.getText().toString() + getResources().getString(R.string.ellipsis);
		progressDialog.setMessage(tempMsg);
		progressDialog.show();
		Controller.getInstance().doRequest(AnnounceDetailActivity.this, UrlType.ANNOUNCE_DETAIL, errorListener, Params.announceDetail(id));
	}

	private void setTopListener() {
		backBtn.setOnClickListener(titleListener);
		homeBtn.setOnClickListener(titleListener);
	}

	private void setListener() {
		setTopListener();
	}

	private OnClickListener titleListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			if (v == homeBtn) {
				Intent it = new Intent(AnnounceDetailActivity.this, MainActivity.class);
				it.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				startActivity(it);
			} else {
				AnnounceDetailActivity.this.finish();
			}
		}
	};

	private ErrorListener errorListener = new ErrorListener() {

		@Override
		public void onSuccess(UrlType type, String json) {
			Loger.d("The Json in detail is :" + json);

			if (progressDialog.isShowing()) {
				progressDialog.dismiss();
			}
			if (detailLayout.getVisibility() == View.INVISIBLE) {
				detailLayout.setVisibility(View.VISIBLE);
			}
			JSONObject detailJson = null;
			try {
				detailJson = new JSONObject(json);
				if (JsonHandle.getInstance().jsonCodeHandle(detailJson) == 0) {

					JSONObject jsonObj = detailJson.getJSONObject("announce");

					((TextView) findViewById(R.id.title_tv)).setText(jsonObj.isNull("oaAnnoName") ? "" : jsonObj.getString("oaAnnoName"));
					((TextView) findViewById(R.id.create_time_tv)).setText(jsonObj.isNull("oaAnnoTime") ? "" : jsonObj.getString("oaAnnoTime"));
					String sddirstr = spHelper.getSavePath();

					if (!jsonObj.isNull("oaAnnoText") && !jsonObj.getString("oaAnnoText").equals("")) {
						WebView view = ((WebView) findViewById(R.id.doc_html_content_html_webview));
						view.getSettings().setDefaultTextEncodingName(HTTP.UTF_8);
						view.loadDataWithBaseURL(ConfigProperties.SERVER_URL, jsonObj.isNull("oaAnnoText") ? "" : jsonObj.getString("oaAnnoText"), "text/html", HTTP.UTF_8, ConfigProperties.SERVER_URL);
					}

					JSONArray jsonArray = detailJson.getJSONArray("attachmentList");
					String[] strArray = { "primaryKey", "attachmentName" };
					list = JsonHandle.getInstance().jsonCodeArrayHandle(list, jsonArray, strArray);

					if (!PhoneStateUtil.exterStorageReady()) {
						for (int i = 0; i < list.size(); i++) {
							list.get(i).put("hasDownLoadState", 0);
						}
					} else {
						spHelper = new SharePrefsHelper(AnnounceDetailActivity.this);
						for (int i = 0; i < list.size(); i++) {
							File file = new File(sddirstr, list.get(i).get("attachmentName").toString());
							if (file.exists()) {
								list.get(i).put("hasDownLoadState", 4);
							} else {
								list.get(i).put("hasDownLoadState", 0);
							}
						}
					}

					listView = (ListView) findViewById(R.id.attach_listview);
					adapter = new DetailAdapter();
					listView.setAdapter(adapter);
				}
			} catch (JSONException e) {

			}

		}

		@Override
		public void onError(UrlType type, ErrorCode code) {
			if (progressDialog.isShowing()) {
				progressDialog.dismiss();
			}
			switch (code) {
			case READW_TIMOUT:
				ToastHelper.showShortMsg(R.string.exception_readw_timeout);
				break;
			case AIRPLANE_MODE:
				ToastHelper.showShortMsg(R.string.exception_airplane_mode);
				break;
			case NO_INTERNET:
				ToastHelper.showShortMsg(R.string.exception_no_internet);
				break;
			case INVALID_IO:
				ToastHelper.showShortMsg(R.string.exception_invaild_io);
				break;
			default:
				break;
			}
		}
	};

	private class DetailAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			if (list != null) {
				return list.size();
			}
			return 0;
		}

		@Override
		public Object getItem(int position) {
			if (list != null) {
				return list.get(position);
			}
			return null;
		}

		@Override
		public long getItemId(int position) {
			if (list != null) {
				return position;
			}
			return 0;
		}

		private class Holder {
			LinearLayout attachRightll;
			ImageView attachImageIv;
			TextView attachStateNameTv;
			TextView attachnameTv;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			Holder holder;
			if (convertView == null) {
				holder = new Holder();
				convertView = View.inflate(AnnounceDetailActivity.this, R.layout.attachfile_item, null);
				holder.attachStateNameTv = (TextView) convertView.findViewById(R.id.attachfile_state_tv);
				holder.attachnameTv = (TextView) convertView.findViewById(R.id.attachfile_item_attachname_tv);
				holder.attachRightll = (LinearLayout) convertView.findViewById(R.id.attachfile_right_ll);
				holder.attachImageIv = (ImageView) convertView.findViewById(R.id.attachfile_state_iv);
				convertView.setTag(holder);// 把workHolder的内容放入tag
			} else {
				// 如果convertView不为空，把之前为空时候放入workHolder的内容读出来
				holder = (Holder) convertView.getTag();
			}

			holder.attachnameTv.setText(list.get(position).get("attachmentName").toString());
			int i = Integer.parseInt(String.valueOf(list.get(position).get("hasDownLoadState")));
			switch (i) {
			case 0:
				holder.attachImageIv.setImageResource(R.drawable.download_normal);
				holder.attachStateNameTv.setText(R.string.download);
				break;
			case 1:
				holder.attachImageIv.setImageResource(R.drawable.download_waiting);
				holder.attachStateNameTv.setText(R.string.download_waiting);
				break;
			case 2:
				holder.attachImageIv.setImageResource(R.drawable.download_process);
				break;
			case 3:
				holder.attachImageIv.setImageResource(R.drawable.download_normal);
				holder.attachStateNameTv.setText(R.string.download_again);
				break;
			case 4:
				holder.attachImageIv.setImageResource(R.drawable.download_finish);
				holder.attachStateNameTv.setText(R.string.download_open);
				break;
			default:
				break;
			}
			holder.attachRightll.setOnClickListener(new DocDownloadListener(position, list.get(position).toString(), holder.attachStateNameTv, holder.attachImageIv));
			return convertView;
		}
	}

	private DocDownloadCallBackListener docCallBack = new DocDownloadCallBackListener() {

		@Override
		public void docCallBack(int position, int result, ImageView iv, TextView tv, ErrorCode errorcode) {
			Loger.d("The pos is" + position + "; The res is:" + result);
			if (result == 1 || result == -1) {
				tv.setText(R.string.download_open);
				list.get(position).put("hasDownLoadState", 4);
				iv.setImageResource(R.drawable.download_finish);
			} else if (result == 0) {
				list.get(position).put("hasDownLoadState", 0);
				tv.setText(R.string.download_again);
				iv.setImageResource(R.drawable.download_normal);
			}
		}
	};

	private class DocDownloadListener implements OnClickListener {
		private int position;
		private TextView tv;
		private ImageView iv;

		public DocDownloadListener(int index, String url, TextView tv, ImageView iv) {
			this.position = index;
			this.tv = tv;
			this.iv = iv;
		}

		@Override
		public void onClick(View v) {
			int i = Integer.parseInt(String.valueOf(list.get(position).get("hasDownLoadState")));
			Loger.d("The i is" + i);
			switch (i) {
			case 0:
			case 3:
				list.get(position).put("hasDownLoadState", 1);
				this.tv.setText(R.string.download_waiting);
				this.iv.setImageResource(R.drawable.download_waiting);
				String url = ConfigProperties.ATTACH_DOWNLOAD_URL + list.get(position).get("primaryKey").toString();
				DocDownloadLoadManager.load(AnnounceDetailActivity.this, spHelper.getSavePath() + list.get(position).get("attachmentName").toString(), url, this.iv, this.tv, position, docCallBack);
				break;
			case 1:
			case 2:
				break;
			case 4:
				String tempPath = spHelper.getSavePath() + list.get(position).get("attachmentName").toString();
				Intent it = new Intent(Intent.ACTION_VIEW);
				it.addCategory(Intent.CATEGORY_DEFAULT);
				it.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				String end = tempPath.substring(tempPath.lastIndexOf(".") + 1, tempPath.length()).toLowerCase();
				String type;
				Uri uri2 = Uri.fromFile(new File(tempPath));
				if (end.equalsIgnoreCase("txt")) {
					type = "text/plain";
				} else if (end.equalsIgnoreCase("xls")) {
					type = "application/vnd.ms-excel";
				} else if (end.equalsIgnoreCase("doc") || end.equalsIgnoreCase("docx")) {
					type = "application/msword";
				} else if (end.equalsIgnoreCase("pdf")) {
					type = "application/pdf";
				} else if (end.equalsIgnoreCase("ppt")) {
					type = "application/vnd.ms-powerpoint";
				} else {
					type = "*/*";
				}
				it.setDataAndType(uri2, type);
				try {
					startActivity(it);
				} catch (ActivityNotFoundException e) {
					ToastHelper.showShortMsg(R.string.sorry_cannotopenit_use_thridsoft);
					return;
				}
				break;
			}

		}
	}

}
